# -*- coding: utf-8 -*-
"""
Supplier Form
Provide form for editing supplier data
"""

from PySide import QtCore, QtGui, QtSql

class _supplierForm(QtGui.QDialog):

    formSaved = QtCore.Signal()

    def __init__(self, database, widgetTitle='Widget Title', parent=None):

        super(_supplierForm, self).__init__(parent)

        self.setMaximumWidth(400)

        self.database = database
        self.setupAttributes()

        self.mainVBoxLayout = QtGui.QVBoxLayout(self)
        self.mainVBoxLayout.setObjectName("mainVBoxLayout")

        self.widgetTitle = QtGui.QLabel(widgetTitle, self)
        self.widgetTitle.setObjectName("widgetTitle")
        self.widgetTitle.font = QtGui.QFont()
        self.widgetTitle.font.setWeight(75)
        self.widgetTitle.font.setBold(True)
        self.widgetTitle.setFont(self.widgetTitle.font)
        self.widgetTitle.setMargin(1)
        self.widgetTitle.setIndent(3)

        self.mainVBoxLayout.addWidget(self.widgetTitle)
        
        #self.line = QtGui.QFrame(self)
        #self.line.setFrameShape(QtGui.QFrame.HLine)
        #self.line.setFrameShadow(QtGui.QFrame.Sunken)
        #self.line.setObjectName("line")

        #self.mainVBoxLayout.addWidget(self.line)

        self.supplierGroupBox = QtGui.QGroupBox(self)
        self.supplierGroupBox.setObjectName("supplierGroupBox")
        
        self.supplierGridLayout = QtGui.QGridLayout(self.supplierGroupBox)
        self.supplierGridLayout.setObjectName("supplierGridLayout")
        
        self.namaSupplierLabel = QtGui.QLabel(self.supplierGroupBox)
        self.namaSupplierLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.namaSupplierLabel.setMargin(9)
        self.namaSupplierLabel.setObjectName("namaSupplierLabel")
        self.supplierGridLayout.addWidget(self.namaSupplierLabel, 0, 0, 1, 1)
        
        self.namaSupplierLineEdit = QtGui.QLineEdit(self.supplierGroupBox)
        self.namaSupplierLineEdit.setObjectName("namaSupplierLineEdit")
        self.supplierGridLayout.addWidget(self.namaSupplierLineEdit, 0, 1, 1, 1)
        
        self.industriLabel = QtGui.QLabel(self.supplierGroupBox)
        self.industriLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.industriLabel.setMargin(9)
        self.industriLabel.setObjectName("industriLabel")
        self.supplierGridLayout.addWidget(self.industriLabel, 1, 0, 1, 1)
    
        self.industriComboBox = QtGui.QComboBox(self.supplierGroupBox)
        #self.industriComboBox.setMinimumContentsLength(1)
        
        self.industriCompleter = QtGui.QCompleter(self.supplierGroupBox)
        self.industriCompleter.setMaxVisibleItems(6)
        
        self.industriQuery = QtSql.QSqlQuery("SELECT id, nama FROM list_industry")
        self.industriModel = QtSql.QSqlTableModel(self.industriCompleter)
        self.industriModel.setQuery(self.industriQuery)

        self.industriCompleter.setModel(self.industriModel)
        self.industriCompleter.setCompletionColumn(1)

        while self.industriQuery.next():
            self.industriComboBox.addItem(self.industriQuery.value(1), self.industriQuery.value(0))            
        self.industriComboBox.setCompleter(self.industriCompleter)
        self.industriComboBox.setEditable(True)
        self.industriCompleter.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.industriCompleter.setCompletionMode(QtGui.QCompleter.InlineCompletion)
        self.industriCompleter.setModelSorting(QtGui.QCompleter.CaseInsensitivelySortedModel)
        self.industriCompleter.setWrapAround(False)
        self.industriComboBox.setObjectName("industriComboBox")
        self.supplierGridLayout.addWidget(self.industriComboBox, 1, 1, 1, 1)
        
        self.alamatLabel = QtGui.QLabel(self.supplierGroupBox)
        self.alamatLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.alamatLabel.setMargin(9)
        self.alamatLabel.setObjectName("alamatLabel")
        self.supplierGridLayout.addWidget(self.alamatLabel, 2, 0, 1, 1)
        
        self.alamatLineEdit = QtGui.QLineEdit(self.supplierGroupBox)
        self.alamatLineEdit.setObjectName("alamatLineEdit")
        self.supplierGridLayout.addWidget(self.alamatLineEdit, 2, 1, 1, 1)
        
        self.kotaLabel = QtGui.QLabel(self.supplierGroupBox)
        self.kotaLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.kotaLabel.setMargin(9)
        self.kotaLabel.setObjectName("kawasanLabel")
        self.supplierGridLayout.addWidget(self.kotaLabel, 3, 0, 1, 1)
        
        self.kotaLineEdit = QtGui.QLineEdit(self.supplierGroupBox)
        self.kotaLineEdit.setObjectName("kawasanLineEdit")
        self.supplierGridLayout.addWidget(self.kotaLineEdit, 3, 1, 1, 1)
        
        self.ponselLabel = QtGui.QLabel(self.supplierGroupBox)
        self.ponselLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.ponselLabel.setMargin(9)
        self.ponselLabel.setObjectName("ponselLabel")
        self.supplierGridLayout.addWidget(self.ponselLabel, 4, 0, 1, 1)
        
        self.ponselLineEdit = QtGui.QLineEdit(self.supplierGroupBox)
        self.ponselLineEdit.setObjectName("ponselLineEdit")
        self.supplierGridLayout.addWidget(self.ponselLineEdit, 4, 1, 1, 1)
        
        self.teleponLabel = QtGui.QLabel(self.supplierGroupBox)
        self.teleponLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.teleponLabel.setMargin(9)
        self.teleponLabel.setObjectName("teleponLabel")
        self.supplierGridLayout.addWidget(self.teleponLabel, 5, 0, 1, 1)
        
        self.teleponLineEdit = QtGui.QLineEdit(self.supplierGroupBox)
        self.teleponLineEdit.setObjectName("teleponLineEdit")
        self.supplierGridLayout.addWidget(self.teleponLineEdit, 5, 1, 1, 1)
        
        self.faxLabel = QtGui.QLabel(self.supplierGroupBox)
        self.faxLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.faxLabel.setMargin(9)
        self.faxLabel.setObjectName("faxLabel")
        self.supplierGridLayout.addWidget(self.faxLabel, 6, 0, 1, 1)
        
        self.faxLineEdit = QtGui.QLineEdit(self.supplierGroupBox)
        self.faxLineEdit.setObjectName("faxLineEdit")
        self.supplierGridLayout.addWidget(self.faxLineEdit, 6, 1, 1, 1)
        
        self.keteranganTextEdit = QtGui.QPlainTextEdit(self.supplierGroupBox)
        self.keteranganTextEdit.setObjectName("keteranganTextEdit")
        self.keteranganTextEdit.setTabChangesFocus(True)
        self.supplierGridLayout.addWidget(self.keteranganTextEdit, 7, 0, 1, 2)        
        self.mainVBoxLayout.addWidget(self.supplierGroupBox)
        
        self.kontakGroupBox = QtGui.QGroupBox(self)
        self.kontakGroupBox.setObjectName("kontakGroupBox")
        
        self.kontakGridLayout = QtGui.QGridLayout(self.kontakGroupBox)
        self.kontakGridLayout.setObjectName("kontakGridLayout")
        
        self.kontakLabel = QtGui.QLabel(self.kontakGroupBox)
        self.kontakLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.kontakLabel.setMargin(9)
        self.kontakLabel.setObjectName("kontakLabel")
        self.kontakGridLayout.addWidget(self.kontakLabel, 0, 0, 1, 1)
        
        self.kontakNamaLineEdit = QtGui.QLineEdit(self.kontakGroupBox)
        self.kontakNamaLineEdit.setObjectName("kontakNamaLineEdit")
        self.kontakGridLayout.addWidget(self.kontakNamaLineEdit, 0, 1, 1, 1)
        
        self.kontakTeleponLabel = QtGui.QLabel(self.kontakGroupBox)
        self.kontakTeleponLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.kontakTeleponLabel.setMargin(9)
        self.kontakTeleponLabel.setObjectName("kontakTeleponLabel")
        self.kontakGridLayout.addWidget(self.kontakTeleponLabel, 1, 0, 1, 1)
        
        self.kontakTeleponLineEdit = QtGui.QLineEdit(self.kontakGroupBox)
        self.kontakTeleponLineEdit.setObjectName("kontakTeleponLineEdit")
        self.kontakGridLayout.addWidget(self.kontakTeleponLineEdit, 1, 1, 1, 1)
        
        self.kontakPonselLabel = QtGui.QLabel(self.kontakGroupBox)
        self.kontakPonselLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
        self.kontakPonselLabel.setMargin(9)
        self.kontakPonselLabel.setObjectName("kontakPonselLabel")
        self.kontakGridLayout.addWidget(self.kontakPonselLabel, 2, 0, 1, 1)
        
        self.kontakPonselLineEdit = QtGui.QLineEdit(self.kontakGroupBox)
        self.kontakPonselLineEdit.setObjectName("kontakPonselLineEdit")
        self.kontakGridLayout.addWidget(self.kontakPonselLineEdit, 2, 1, 1, 1)
        
        self.mainVBoxLayout.addWidget(self.kontakGroupBox)
        
        spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.mainVBoxLayout.addItem(spacerItem)
        
        self.buttonBox = QtGui.QDialogButtonBox(self)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.mainVBoxLayout.addWidget(self.buttonBox)
        
        self.namaSupplierLabel.setBuddy(self.namaSupplierLineEdit)
        self.industriLabel.setBuddy(self.industriComboBox)
        self.alamatLabel.setBuddy(self.alamatLineEdit)
        self.kotaLabel.setBuddy(self.kotaLineEdit)
        self.ponselLabel.setBuddy(self.ponselLineEdit)
        self.teleponLabel.setBuddy(self.teleponLineEdit)
        self.faxLabel.setBuddy(self.faxLineEdit)
        self.kontakLabel.setBuddy(self.kontakNamaLineEdit)
        self.kontakTeleponLabel.setBuddy(self.kontakTeleponLineEdit)
        self.kontakPonselLabel.setBuddy(self.kontakPonselLineEdit)

        self.retranslateUi()

        # FIX:
        # anomaly behaviour
        self.buttonBox.button(QtGui.QDialogButtonBox.Cancel).clicked.connect(self.hide)


    def retranslateUi(self):
        self.supplierGroupBox.setTitle(QtGui.QApplication.translate(self.objectName(), "Supplier", None, QtGui.QApplication.UnicodeUTF8))
        self.namaSupplierLabel.setText(QtGui.QApplication.translate(self.objectName(), "&Nama", None, QtGui.QApplication.UnicodeUTF8))
        self.industriLabel.setText(QtGui.QApplication.translate(self.objectName(), "&Industri", None, QtGui.QApplication.UnicodeUTF8))
        self.alamatLabel.setText(QtGui.QApplication.translate(self.objectName(), "&Alamat", None, QtGui.QApplication.UnicodeUTF8))
        self.kotaLabel.setText(QtGui.QApplication.translate(self.objectName(), "Ka&wasan", None, QtGui.QApplication.UnicodeUTF8))
        self.ponselLabel.setText(QtGui.QApplication.translate(self.objectName(), "&Ponsel", None, QtGui.QApplication.UnicodeUTF8))
        self.teleponLabel.setText(QtGui.QApplication.translate(self.objectName(), "&Telepon", None, QtGui.QApplication.UnicodeUTF8))
        self.faxLabel.setText(QtGui.QApplication.translate(self.objectName(), "&Fax", None, QtGui.QApplication.UnicodeUTF8))
        self.kontakGroupBox.setTitle(QtGui.QApplication.translate(self.objectName(), "Kontak", None, QtGui.QApplication.UnicodeUTF8))
        self.kontakLabel.setText(QtGui.QApplication.translate(self.objectName(), "Na&ma", None, QtGui.QApplication.UnicodeUTF8))
        self.kontakTeleponLabel.setText(QtGui.QApplication.translate(self.objectName(), "T&elepon", None, QtGui.QApplication.UnicodeUTF8))
        self.kontakPonselLabel.setText(QtGui.QApplication.translate(self.objectName(), "P&onsel", None, QtGui.QApplication.UnicodeUTF8))

    
    def setupAttributes(self):
        self.last_edit_id = None


    def reject(self):
        # Dipanggil saat tombol close(X) diklik
        print self
        print 'parent reject'
        super(_supplierForm, self).reject()


    def hide(self):
        # Dipanggil saat tombol cancel diklik
        print self
        print 'parent hide'
        super(_supplierForm, self).reject()



class supplierNewForm(_supplierForm):

    def __init__(self, database, widgetTitle='supplier New Form', parent=None):

        super(supplierNewForm, self).__init__(database, widgetTitle, parent)

        self.setObjectName('supplierNewForm')

        self.buttonBox.button(QtGui.QDialogButtonBox.Ok).clicked.connect(self.addSupplier)


    def addSupplier(self):
        # Create new insert query here
        self.query = QtSql.QSqlQuery()
        self.query.prepare("INSERT INTO db_supplier(`id`, "
                                                   "`supplier_nama`, "
                                                   "`db_industry_id`, "
                                                   "`alamat`, "
                                                   "`kota`, "
                                                   "`ponsel`, "
                                                   "`telp`, "
                                                   "`fax`, "
                                                   "`keterangan`, "
                                                   "`kontak_nama`, "
                                                   "`kontak_telp`, "
                                                   "`kontak_ponsel`) "
                                            "VALUE(:id, "
                                                  ":supplier_nama, "
                                                  ":db_industry_id, "
                                                  ":alamat, "
                                                  ":kota, "
                                                  ":ponsel, "
                                                  ":telp, "
                                                  ":fax, "
                                                  ":keterangan, "
                                                  ":kontak_nama, "
                                                  ":kontak_telp, "
                                                  ":kontak_ponsel)")
        self.query.bindValue(":id", '')
        self.query.bindValue(":supplier_nama", self.namaSupplierLineEdit.text())
        self.query.bindValue(":db_industry_id", self.industriComboBox.itemData(self.industriComboBox.currentIndex()))
        self.query.bindValue(":alamat", self.alamatLineEdit.text())
        self.query.bindValue(":kota", self.kotaLineEdit.text())
        self.query.bindValue(":ponsel", self.ponselLineEdit.text())
        self.query.bindValue(":telp", self.teleponLineEdit.text())
        self.query.bindValue(":fax", self.faxLineEdit.text())
        self.query.bindValue(":keterangan", self.keteranganTextEdit.toPlainText())
        self.query.bindValue(":kontak_nama", self.kontakNamaLineEdit.text())
        self.query.bindValue(":kontak_telp", self.kontakTeleponLineEdit.text())
        self.query.bindValue(":kontak_ponsel", self.kontakPonselLineEdit.text())

        print self.query.boundValues()
        #return

        if self.query.exec_():
           print 'Save Supplier OK'
           print self.query.lastQuery()
           self.formSaved.emit()
           # Sembunyikan form
           self.done(1)
        else:
           print 'Save Supplier Failed'
           print self.query.lastQuery()
           print self.query.lastError()

    # FIX:
    # problem: dialog still appear when done adding new item
    # so, any done operation on the dialog, be it cancel, close or ok
    # we should hide it afterward


    def reject(self):
        # Dipanggil saat tombol close(X) diklik
        print self
        print 'reject'
        super(supplierNewForm, self).reject()


    def hide(self):
        # Dipanggil saat tombol cancel diklik
        print self
        print 'hide'
        super(supplierNewForm, self).reject()


    def __del__(self):
        print 'o, im dead'



class supplierEditForm(_supplierForm):

    def __init__(self, database, widgetTitle='supplier Edit Form', parent=None):

        super(supplierEditForm, self).__init__(database, widgetTitle, parent)

        self.setObjectName('supplierEditForm')

        self.buttonBox.button(QtGui.QDialogButtonBox.Ok).clicked.connect(self.saveSupplier)


    def editSupplier(self, supplier_id):
        if type(supplier_id) is not int:
            return
        
        itemQuery = QtSql.QSqlQuery("SELECT `id`, "
                                           "`supplier_nama`, "
                                           "`db_industry_id`, "
                                           "`alamat`, "
                                           "`kota`, "
                                           "`ponsel`, "
                                           "`telp`, "
                                           "`fax`, "
                                           "`situs`, "
                                           "`email`, "
                                           "`keterangan`, "
                                           "`kontak_nama`, "
                                           "`kontak_ponsel`, "
                                           "`kontak_telp` "
                                           " FROM `db_supplier` WHERE `id`=%s" % supplier_id)
        print itemQuery.lastQuery()
        while itemQuery.next():
            self.namaSupplierLineEdit.setText(itemQuery.value(1))
            self.industriComboBox.setCurrentIndex(self.industriComboBox.findData(itemQuery.value(2)))
            self.alamatLineEdit.setText(itemQuery.value(3))
            self.kotaLineEdit.setText(itemQuery.value(4))
            self.ponselLineEdit.setText(itemQuery.value(5))
            self.teleponLineEdit.setText(itemQuery.value(6))
            self.faxLineEdit.setText(itemQuery.value(7))
            #self.situsLineEdit.setText(itemQuery.value(8))
            #self.emailLineEdit.setText(itemQuery.value(9))
            self.keteranganTextEdit.setPlainText(itemQuery.value(10))
            self.kontakNamaLineEdit.setText(itemQuery.value(11))
            self.kontakPonselLineEdit.setText(itemQuery.value(12))
            self.kontakTeleponLineEdit.setText(itemQuery.value(13))

            self.last_edit_id = itemQuery.value(0)

        itemQuery.clear()

    def saveSupplier(self):
        if self.last_edit_id is not None:
            self.query = QtSql.QSqlQuery()
            self.query.prepare("UPDATE db_supplier SET supplier_nama = :supplier_nama, "
                                                      "db_industry_id = :db_industry_id, "
                                                      "alamat = :alamat, "
                                                      "kota = :kota, "
                                                      "ponsel = :ponsel, "
                                                      "telp = :telp, "
                                                      "fax = :fax, "
                                                      "keterangan = :keterangan, "
                                                      "kontak_nama = :kontak_nama, "                                                      
                                                      "kontak_telp = :kontak_telp, "
                                                      "kontak_ponsel = :kontak_ponsel "
                                                      "WHERE id = :id")
            
            self.query.bindValue(":supplier_nama", self.namaSupplierLineEdit.text())
            self.query.bindValue(":db_industry_id", self.industriComboBox.itemData(self.industriComboBox.currentIndex()))
            self.query.bindValue(":alamat", self.alamatLineEdit.text())
            self.query.bindValue(":kota", self.kotaLineEdit.text())
            self.query.bindValue(":ponsel", self.ponselLineEdit.text())
            self.query.bindValue(":telp", self.teleponLineEdit.text())
            self.query.bindValue(":fax", self.faxLineEdit.text())
            self.query.bindValue(":keterangan", self.keteranganTextEdit.toPlainText())
            self.query.bindValue(":kontak_nama", self.kontakNamaLineEdit.text())
            self.query.bindValue(":kontak_telp", self.kontakTeleponLineEdit.text())
            self.query.bindValue(":kontak_ponsel", self.kontakPonselLineEdit.text())
            self.query.bindValue(":id", self.last_edit_id)

            print self.query.boundValues()
            #return
    
            if self.query.exec_():
               print 'Save Supplier OK'
               print self.query.lastQuery()
               print 'Sembunyikan diri'
               self.formSaved.emit()
               self.done(1)
            else:
               print 'Save Supplier Failed'
               print self.query.lastQuery()
               print self.query.lastError()



class supplierRemoveForm(QtGui.QMessageBox):

    supplierRemoved = QtCore.Signal()

    def __init__(self, database, boxTitle):
        super(supplierRemoveForm, self).__init__()
        self.setText("Hapus supplier");
        self.setStandardButtons(self.Ok | self.Cancel);
        self.setDefaultButton(self.Ok);
        self.buttonOk = self.button(self.Ok)
        self.buttonCancel = self.button(self.Cancel)

        self.buttonClicked.connect(self.removeItem)


    def removeSupplier(self, supplier_id, supplier_nama):

        self.supplier_id = supplier_id
        self.supplier_nama = supplier_nama

        self.setInformativeText("Apakah Anda ingin menghapus supplier no. <i>%s</i>: <b>%s</b>?" % (self.supplier_id, self.supplier_nama));


    def removeItem(self, button):
        print button, self.buttonOk, self.buttonCancel
        if button == self.buttonOk:
            self.query = QtSql.QSqlQuery()
            self.query.prepare("DELETE FROM `db_supplier` WHERE `id`=%s" % self.supplier_id)
            print self.query.boundValues()
            if self.query.exec_():
                self.query.lastQuery()
                self.supplierRemoved.emit()
                print 'removing supplier %s:%s done' % (self.supplier_id, self.supplier_nama)
            else:
                print 'removing supplier %s:%s error' % (self.supplier_id, self.supplier_nama)
                print self.query.lastQuery()
                print self.query.lastError()
        else:
            print 'removing supplier %s:%s canceled' % (self.supplier_id, self.supplier_nama)





        
"""
TODO:
1. Emit Error, emit is found on QtCore.QObject().emit()
2. Form validation, karena baik addSupplier maupun editSupplier masih mengizinkan field-field kosong.
"""
